class Main extends egret.DisplayObjectContainer {

    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
    }

    private onAddToStage(event: egret.Event) {

        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin

            context.onUpdate = () => {

            }
        })

        egret.lifecycle.onPause = () => {
            egret.ticker.pause();
        }

        egret.lifecycle.onResume = () => {
            egret.ticker.resume();
        }

        this.runGame().catch(e => {
            console.log(e);
        })



    }

    private async runGame() {
        await this.loadResource()
        this.createGameScene();
        const result = await RES.getResAsync("description_json")
        this.startAnimation(result);
        await platform.login();
        const userInfo = await platform.getUserInfo();
        console.log(userInfo);

    }

    private async loadResource() {
        try {
            const loadingView = new LoadingUI();
            this.stage.addChild(loadingView);

            // 加载资源配置
            await RES.loadConfig("resource/default.res.json", "resource/");
            await RES.loadGroup("preload", 0, loadingView);
            this.stage.removeChild(loadingView);
        }
        catch (e) {
            console.error(e);
        }
    }

    private textfield: egret.TextField;
    private websocket:egret.WebSocket;

    /**
     * 创建游戏场景
     * Create a game scene
     */
    private createGameScene() {
        var bg:egret.Shape = new egret.Shape();
        bg.graphics.beginFill(0x336699);
        bg.graphics.drawRect(0, 0, this.stage.stageWidth, this.stage.stageHeight);
        bg.graphics.endFill;
        this.addChild(bg);

        var tx:egret.TextField = new egret.TextField();
        tx.text = "文字内容";
        tx.size = 20;
        tx.touchEnabled = true;
        tx.x = 300;
        tx.y = 40;
        tx.addEventListener(egret.TouchEvent.TOUCH_TAP, this.touchHandler, this);
        this.addChild(tx);

        let sky = this.createBitmapByName("bg_jpg");
        this.addChild(sky);
     

        this.setChildIndex(tx, this.getChildIndex(sky));


        this.websocket = new egret.WebSocket();
        this.websocket.addEventListener(egret.ProgressEvent.SOCKET_DATA, this.onReceiveMessage,this);
        this.websocket.addEventListener(egret.Event.CONNECT, this.onSocketOpen, this);
        this.websocket.connect("echo.websocket.org", 80);


        // let stageW = this.stage.stageWidth;
        // let stageH = this.stage.stageHeight;
        // sky.width = stageW;
        // sky.height = stageH;

        // let topMask = new egret.Shape();
        // topMask.graphics.beginFill(0x000000, 0.5);
        // topMask.graphics.drawRect(0, 0, stageW, 172);
        // topMask.graphics.endFill();
        // topMask.y = 33;
        // this.addChild(topMask);

        // let icon = this.createBitmapByName("egret_icon_png");
        // this.addChild(icon);
        // icon.x = 26;
        // icon.y = 33;

        // let line = new egret.Shape();
        // line.graphics.lineStyle(2, 0xffffff);
        // line.graphics.moveTo(0, 0);
        // line.graphics.lineTo(0, 117);
        // line.graphics.endFill();
        // line.x = 172;
        // line.y = 61;
        // this.addChild(line);


        // let colorLabel = new egret.TextField();
        // colorLabel.textColor = 0xffffff;
        // colorLabel.width = stageW - 172;
        // colorLabel.textAlign = "center";
        // colorLabel.text = "Hello 白鹭";
        // colorLabel.size = 24;
        // colorLabel.x = 172;
        // colorLabel.y = 80;
        // this.addChild(colorLabel);

        // let textfield = new egret.TextField();
        // this.addChild(textfield);
        // textfield.alpha = 0;
        // textfield.width = stageW - 172;
        // textfield.textAlign = egret.HorizontalAlign.CENTER;
        // textfield.size = 24;
        // textfield.textColor = 0xffffff;
        // textfield.x = 172;
        // textfield.y = 135;
        // this.textfield = textfield;
    }

    private onSocketOpen(evt:egret.Event):void{
        var cmd = "My Egret Test";
        console.log("webSocket: " + cmd);
        this.websocket.writeUTF(cmd);
    }

    private onReceiveMessage(evt:egret.ProgressEvent):void{
        var msg = this.websocket.readUTF();
        console.log("websocket: " + msg);
    }

    private touchHandler(evt:egret.TouchEvent):void{
        // var sound:egret.Sound = RES.getRes("bg_music");
        // var channel:egret.SoundChannel = sound.play(0,1);

        // var tx:egret.TextField = evt.currentTarget;
        // tx.textColor = 0x00ff00;

        // egret.Tween.get(tx).to({alpha:.3},300, egret.Ease.circIn).to({alpha:1}, 300, egret.Ease.circIn).to({scaleX:4,scaleY:4}, 1000, egret.Ease.circIn)
        // .to({scaleX:1,scaleY:1}, 1000,egret.Ease.circIn);

        // var urlreq:egret.URLRequest = new egret.URLRequest("http://httpbin.org/user-agent");
        // var urlloader:egret.URLLoader = new egret.URLLoader();
        // urlloader.addEventListener(egret.Event.COMPLETE, function(evt:egret.Event):void{
        //     console.log(evt.target.data);
        // }, this);
        // urlloader.load(urlreq);

    }

    /**
     * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
     * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
     */
    private createBitmapByName(name: string) {
        let result = new egret.Bitmap();
        let texture: egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }

    /**
     * 描述文件加载成功，开始播放动画
     * Description file loading is successful, start to play the animation
     */
    private startAnimation(result: string[]) {
        let parser = new egret.HtmlTextParser();

        let textflowArr = result.map(text => parser.parse(text));
        let textfield = this.textfield;
        let count = -1;
        let change = () => {
            count++;
            if (count >= textflowArr.length) {
                count = 0;
            }
            let textFlow = textflowArr[count];

            // 切换描述内容
            // Switch to described content
            textfield.textFlow = textFlow;
            let tw = egret.Tween.get(textfield);
            tw.to({ "alpha": 1 }, 200);
            tw.wait(2000);
            tw.to({ "alpha": 0 }, 200);
            tw.call(change, this);
        };

        change();
    }
}